package com.kcwl.carrier.application.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.kcwl.carrier.domain.entity.AuditRejectReasonInfo;
import com.kcwl.carrier.domain.service.AuditRejectReasonDomainService;
import com.kcwl.carrier.infrastructure.constant.CarrierConstant;
import com.kcwl.carrier.infrastructure.utils.DateUtil;
import com.kcwl.carrier.interfaces.dto.AuditRejectReasonInfoDTO;
import com.kcwl.carrier.interfaces.query.AuditRejectReasonQuery;
import com.kcwl.framework.utils.KcBeanConverter;
import com.kcwl.framework.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;

/**
 * @author 刘旭超
 * @date 2022年12月01日 15:52
 * @Description
 */
@Slf4j
@Service
public class AuditRejectReasonApplicationService {

    @Autowired
    private AuditRejectReasonDomainService domainService;
    @Autowired
    private Gson gson;

    public List<AuditRejectReasonInfoDTO> queryRejectReason(AuditRejectReasonQuery query) {
        List<AuditRejectReasonInfo> list = domainService.queryRejectReason(query);
        return KcBeanConverter.toList(list, AuditRejectReasonInfoDTO.class);
    }

    public List<AuditRejectReasonInfoDTO> queryAllRejectReason() {
        List<AuditRejectReasonInfo> auditRejectReasonInfoList = domainService.queryAllRejectReason();
        return KcBeanConverter.toList(auditRejectReasonInfoList, AuditRejectReasonInfoDTO.class);
    }

    /**
     * 处理返回的历史驳回原因，数智，超管看
     * @param historyRemark
     * @return
     */
    public List<Map<String, Object>> processRemark(String historyRemark) {
        if (StringUtil.isEmpty(historyRemark)) {
            return new ArrayList<>();
        }
        Map<String, Object> map = gson.fromJson(historyRemark, Map.class);
        String remark = (String) map.get("remark");
        String updateTime = (String) map.get("updateTime");
        String[] remarks = remark.split("@");
        String[] updateTimes = updateTime.split("@");
        List<Map<String, Object>> lists = new ArrayList<>();
        if (remarks.length > 1) {
            for (int i = 0; i < remarks.length; i++) {
                Map<String, Object> resMap = new HashMap<>();
                resMap.put("remark", remarks[i]);
                resMap.put("updateTime", updateTimes[i]);
                lists.add(resMap);
            }
        } else {
            lists.add(map);
        }
        return lists;
    }

    /**
     * 处理前端传入为[]的情况
     * @param rejectReason
     * @return
     */
    public String formattedRejectReason(String rejectReason) {
        if (StringUtil.isEmpty(rejectReason)) {
            return rejectReason;
        }
        Map map = JSON.parseObject(rejectReason);
        Iterator<Object> iterator = map.keySet().iterator();
        while(iterator.hasNext()) {
            Object key = iterator.next();
            Object objValue = map.get(key);
            if (objValue instanceof JSONArray) {
                JSONArray list = (JSONArray) objValue;
                if (CollectionUtils.isEmpty(list)) {
                    iterator.remove();
                    map.remove(key);
                }
                continue;
            }

            if (StringUtil.isEmpty(objValue)) {
                iterator.remove();
                map.remove(key);
            }
        }

        return JSONObject.toJSONString(map);
    }

    /**
     * 处理历史驳回原因，数智看
     * @param authenticationRemark
     * @param historyRemark
     * @return
     */
    public String syncHistoryRemark(String authenticationRemark,String historyRemark) {
        //设置最大的历史评论字符长度
        int maxLength = 10000;
        Map<String, String> map = new HashMap<>();
        if (!com.kcwl.framework.utils.StringUtil.isEmpty(authenticationRemark)) {
            if (!com.kcwl.framework.utils.StringUtil.isEmpty(historyRemark)) {
                Map historyMap = gson.fromJson(historyRemark, Map.class);
                String remark = (String) historyMap.get("remark");
                String updateTime = (String) historyMap.get("updateTime");
                map.put("remark", authenticationRemark + "@" + remark);
                map.put("updateTime", DateUtil.getCurDate() + "@" + updateTime);
                //如果超过一千字符长度，就删除历史评论，只记当前评论
                if(gson.toJson(map).length()>maxLength){
                    map.put("remark",authenticationRemark);
                    map.put("updateTime",DateUtil.getCurDate());
                    log.debug("==========historyRemark not empty============Carrier_history_length:"+gson.toJson(map).length());
                }
            } else {
                map.put("remark", authenticationRemark);
                map.put("updateTime", DateUtil.getCurDate());
                log.debug("==========historyRemark-empty============Carrier_history_length:"+gson.toJson(map).length());
            }
            log.debug("=================remark: "+gson.toJson(map));
            return gson.toJson(map);
        }
        return historyRemark;
    }

    /**
     * 处理详细驳回原因，司机端端看
     * @param rejectReason
     * @return
     */
    public String syncAuditRemark(String rejectReason) {
        Map map = JSONObject.parseObject(rejectReason);
        StringBuilder sb = new StringBuilder();
        map.keySet().forEach(s -> {
            if (CarrierConstant.CUSTOM_REJECT_REASON.equals(s)) {
                sb.append(map.get(s)).append(",");
            } else {
                List<Integer> strings = (List<Integer>) map.get(s);
                if (strings.size() > 0) {
                    for (Integer id : strings) {
                        AuditRejectReasonInfo auditRejectReason = domainService.selectId(id.longValue());
                        if (auditRejectReason != null) {
                            sb.append(auditRejectReason.getDetailReason()).append(",");
                        }
                    }
                }
            }
        });
        return sb.substring(0, sb.toString().length() - 1);
    }
}
